<?php
namespace app\common\model;

use think\Model;
use think\Db;

class Goods extends Model
{
	// 关联sku
	public function goodsSku()
	{
		return $this->hasMany('GoodsSku')
			->field('sku_id,goods_id,sku_name,realprice,oldprice,stock,sales');
	}
	// 关联商家信息
	public function shop()
	{
		return $this->belongsTo('User', 'shop_id', 'uid')
			->field('name as shop_name,tel as shop_tel,uid');
	}

	// 关联商品分类
	public function goodsCate()
	{
		return $this->belongsTo('GoodsCate', 'cate_id', 'id')
			->field('id,cate_name,cate_pic');
	}

	/**
	 * 商品列表
	 * 
	 * @param  [type] $map [description]
	 * @return [type]      [description]
	 */
	public function getList($map = [], $size = null)
	{
		return $this->with('goodsSku,shop,goodsCate')->where($map)->order('sort desc')->paginate($size);
	}

	/**
	 * 商品详情
	 * 
	 * @return [type] [description]
	 */
	public function getInfo($gid)
	{
		$info = $this->with('goodsSku,shop')
			->field('sales,sort,update_time,create_time',true)
			->find($gid);

		return $info;
	}

	/**
	 * 添加商品
	 * 
	 * @param [type] $data [description]
	 */
	public function addInfo($data)
	{
		Db::startTrans();
		try {
			$goods_id = $this->insertGetId($data, 'id');
			foreach ($data['sku_list'] as $v) {
				$v['goods_id'] = $goods_id;
				Db::name('goods_sku')->insert($v);
			}

			Db::commit();
			return msg_code('添加成功',1);
		} catch (Exception $e) {
			Db::rollback();
			return msg_code($e->getMessage());
		}
		
	}

	/**
	 * 商品，属性操作
	 * 
	 * @param  [type] $data 修改商品
	 * @return [type]      [description]
	 */
	public function editInfo($data)
	{
		Db::startTrans();
		try {
			$this->where('id', $data['id'])->update($data);
			foreach ($data['sku_list'] as $v) {
				if (isset($v['sku_id'])) {
					Db::name('goods_sku')->where('sku_id', $v['sku_id'])->update($v);
				} else {
					$v['goods_id'] = $data['id'];
					Db::name('goods_sku')->insert($v);
				}
				
			}
			Db::commit();
			return msg_code('操作成功', 1);
		} catch (Exception $e) {
			Db::rollback();
			return msg_code($e->getMessage());
		}
	}

	/**
	 * 变更商品状态
	 *
	 * @param [type] $id
	 * @param [type] $status
	 * @return void
	 */
	public function modifyStatus($id,$data) 
	{
		if ($id) {
			if ($this->where('id', $id)->update($data)) {
				return ['code'=>1,'msg'=>'操作成功'];
			}
		}
		return ['code'=>0,'msg'=>'稍后重试'];
	}



}